/*
 * Copyright (C) 2011 The Code Bakers
 * Authors: Cleuton Sampaio e Francisco Rodrigues
 * e-mail: thecodebakers@gmail.com
 * Project: http://code.google.com/p/biomago/
 * Site: http://thecodebakers.blogspot.com
 *
 * Licensed under the GNU GPL, Version 3.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://gplv3.fsf.org/
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 * @author Cleuton Sampaio e Francisco Rogrigues - thecodebakers@gmail.com
 */
package br.com.thecodebakers.biomago.persistence;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;

import br.com.thecodebakers.biomago.R;
import br.com.thecodebakers.biomago.model.Elemento;
import android.os.Environment;
import android.util.Log;

public class FileAdapter {
	private static final String TAG = "FileAdapter";
	public static List<Elemento> lista;

	public static int saveList() {
		int returnCode = R.string.msg_inclusao_ok;
		String state = Environment.getExternalStorageState();
		String dirName = "/thecodebakers/biomago";
		if (Environment.MEDIA_MOUNTED.equals(state)) {
			try {
				File dir = new File(Environment.getExternalStorageDirectory().toString() + dirName);
				if (!dir.exists()) {
					dir.mkdirs();
				}
				FileOutputStream fileOut = new FileOutputStream(dir.getPath() + "/backup.bin");
				ObjectOutputStream out = new ObjectOutputStream(fileOut);
				out.writeObject(lista);
			}
			catch (Exception ex) {
				Log.e(TAG, "Exception ao salvar: " + ex.getMessage());
				returnCode = R.string.msg_erro_sdcard;
			}
		}
		else {
			returnCode = R.string.msg_erro_sdcard;
		}

		return returnCode;
	}
	
	public static int retrievetList() {
		int returnCode = 0;
		String state = Environment.getExternalStorageState();
		String dirName = "/thecodebakers/biomago";
		lista = new ArrayList<Elemento>();
		if (Environment.MEDIA_MOUNTED.equals(state)) {
			try {
				File arq = new File(Environment.getExternalStorageDirectory().toString() + dirName + "/backup.bin");
				if (arq.exists()) {
					FileInputStream fileIn = new FileInputStream(arq);
					ObjectInputStream in = new ObjectInputStream(fileIn);
					lista = (List<Elemento>) in.readObject();
				}
				else {
					returnCode = R.string.msg_backup_inexistente;
				}
			}
			catch (Exception ex) {
				Log.e(TAG, "Exception ao ler: " + ex.getLocalizedMessage());
				returnCode = R.string.msg_erro_lendo_sdcard;
			}
		}
		return returnCode;
	}
}
